package com.likou;

import java.util.Arrays;
import java.util.Deque;
import java.util.LinkedList;
import java.util.List;

/**
 * Author: 陈桂明
 * Date: 2025/4/16 17:02
 * Description: q394
 */
public class q394 {
    public static void main(String[] args) {
        String s = new q394().decodeString("3[a]2[bc]");
        System.out.println(s);
    }

    public String decodeString(String s) {
        List<Character> list = new LinkedList<>();
        int index = 0;
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if (c != ']') {
                list.add(c);
                index++;
            } else {
                StringBuilder ans = new StringBuilder();
                while (true) {
                    if (list.get(index - 1) != '[') {
                        ans.append(list.get(index - 1));
                        index--;
                        list.remove(index);
                    } else if (list.get(index - 1) == '[') {
                        index--;
                        list.remove(index);

                        StringBuilder builder = new StringBuilder();
                        while (index >= 1 && (int) list.get(index - 1) - '0' >= 0 && (int) list.get(index - 1) - '0' <= 9) {
                            int num_ = list.get(index - 1) - '0';
                            builder.append(num_);
                            index--;
                            list.remove(index);
                        }
                        StringBuilder reverse = builder.reverse();
                        int num = Integer.parseInt(String.valueOf(reverse));

                        for (int j = 0; j < num; j++) {
                            for (int k = ans.length() - 1; k >= 0; k--) {
                                list.add(ans.charAt(k));
                                index++;
                            }
                        }
                        break;
                    }
                }
            }

        }
        // System.out.println(list);

        StringBuilder ans = new StringBuilder();
        for (char c : list) {
            ans.append(c);
        }

        return ans.toString();
    }
}
